﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.MaterialForm;
using System.Threading.Tasks;
using static BW.Mes.WinForms.BasicData.ProductForm;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddProductForm : XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private bool isEdit = false;
        private long editId = 0;
        private string originalCreatedAt = null;

        public AddProductForm()
        {
            InitializeComponent();
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };
            _httpClient = new HttpClient(handler);
            this.Load += AddProductForm_Load;
            this.Load += AddProductForm_AutoGenProductCode;
            this.Text = "新增产品信息";
            btnOK.Text = "确定";
            textEditMsg.EditValueChanged += TextEditMsg_EditValueChanged;
            // 初始化时同步计数
            labelControlCount.Text = $"字符数: {textEditMsg.Text.Length}/50";
        }

        public AddProductForm(ProductModel model) : this()
        {
            if (model != null)
            {
                isEdit = true;
                editId = model.Id;
                textEditCode.Text = model.ProductCode;
                textEditName.Text = model.ProductName;
                textEditSpec.Text = model.Specification;
                comboBoxEditUnit.Text = model.Unit;
                textEditWarning.Text = model.Warning.ToString();
                comboBoxEditGroupType.Text = model.MaterialType;
                textEditMsg.Text = model.ProductMsg;
                lookUpEditGroup.EditValue = model.MaterialId;
                this.Text = "修改产品信息";
                btnOK.Text = "保存";
            }
        }

        private async void AddProductForm_Load(object sender, EventArgs e)
        {
            comboBoxEditUnit.Properties.Items.AddRange(new string[] { "毫米", "厘米", "米", "克", "千克", "个", "次数", "小时" });
            comboBoxEditUnit.Properties.NullText = "请选择单位";
            comboBoxEditGroupType.Properties.Items.Clear();
            comboBoxEditGroupType.Properties.Items.AddRange(new string[] { "半成品", "成品", "原材料", "其他" });
            comboBoxEditGroupType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBoxEditGroupType.Properties.NullText = "请选择群组类型";
            await LoadMaterialGroups();
        }

        private async void AddProductForm_AutoGenProductCode(object sender, EventArgs e)
        {
            // 自动生成产品编号
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"CP{today}";
            int maxSerial = 0;
            try
            {
                var response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Product/GetProduct");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(json);
                    var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                    if (listToken != null)
                    {
                        var products = JsonConvert.DeserializeObject<List<ProductModel>>(listToken.ToString());
                        if (products != null)
                        {
                            foreach (var item in products)
                            {
                                string code = item.ProductCode;
                                if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                {
                                    string serialStr = code.Substring(prefix.Length);
                                    if (int.TryParse(serialStr, out int serial))
                                    {
                                        if (serial > maxSerial) maxSerial = serial;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textEditCode.Text = newCode;
            textEditCode.Properties.ReadOnly = true;
        }

        private async Task LoadMaterialGroups()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/T2/Material/GetMaterial");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var groups = JsonConvert.DeserializeObject<List<MaterialModel>>(dataJson);

                    lookUpEditGroup.Properties.DataSource = groups;
                    lookUpEditGroup.Properties.DisplayMember = "MaterialName";
                    lookUpEditGroup.Properties.ValueMember = "Id";
                    lookUpEditGroup.Properties.NullText = "请选择物料群组";
                    lookUpEditGroup.Properties.Columns.Clear();
                    lookUpEditGroup.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("MaterialName", "物料名称"));
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载物料群组失败: {ex.Message}", "错误");
            }
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            if (lookUpEditGroup.EditValue == null)
            {
                XtraMessageBox.Show("请选择一个物料群组。");
                return;
            }
            if (string.IsNullOrWhiteSpace(comboBoxEditUnit.Text))
            {
                XtraMessageBox.Show("请选择单位。");
                return;
            }
            var selectedGroup = lookUpEditGroup.GetSelectedDataRow() as MaterialModel;
            string materialName = selectedGroup != null ? selectedGroup.MaterialName : "";
            if (isEdit)
            {
                // 修改
                var model = new
                {
                    Id = editId,
                    ProductCode = textEditCode.Text,
                    ProductName = textEditName.Text,
                    Specification = textEditSpec.Text,
                    Unit = comboBoxEditUnit.Text,
                    Warning = int.TryParse(textEditWarning.Text, out int w) ? w : 0,
                    MaterialId = (long)lookUpEditGroup.EditValue,
                    MaterialType = comboBoxEditGroupType.Text,
                    MaterialName = materialName,
                    ProductMsg = textEditMsg.Text,
                    createdBy = "wyj",
                    createdAt = originalCreatedAt,
                    updatedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
                };
                try
                {
                    var json = JsonConvert.SerializeObject(model);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await _httpClient.PutAsync($"{_apiBaseUrl}/T2/Product/UpdateProduct", content);
                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("修改成功！");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"修改失败：{response.ReasonPhrase} - {errorContent}");
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"提交数据时出错: {ex.Message}", "错误");
                }
            }
            else
            {
                // 新增
                var model = new
                {
                    ProductCode = textEditCode.Text,
                    ProductName = textEditName.Text,
                    Specification = textEditSpec.Text,
                    Unit = comboBoxEditUnit.Text,
                    Warning = int.TryParse(textEditWarning.Text, out int w) ? w : 0,
                    MaterialId = (long)lookUpEditGroup.EditValue,
                    MaterialType = comboBoxEditGroupType.Text,
                    MaterialName = materialName,
                    ProductMsg = textEditMsg.Text,
                    createdBy = "wyj",
                    createdAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
                };
                try
                {
                    var json = JsonConvert.SerializeObject(model);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await _httpClient.PostAsync($"{_apiBaseUrl}/T2/Product/AddProduct", content);
                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("添加成功！");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"提交数据时出错: {ex.Message}", "错误");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lookUpEditGroup_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void AddProductForm_Load_1(object sender, EventArgs e)
        {

        }

        private void TextEditMsg_EditValueChanged(object sender, EventArgs e)
        {
            var memoEdit = sender as DevExpress.XtraEditors.MemoEdit;
            if (memoEdit != null)
            {
                string text = memoEdit.Text;
                if (text.Length > 50)
                {
                    text = text.Substring(0, 50);
                    memoEdit.Text = text;
                }
                labelControlCount.Text = $"字符数: {text.Length}/50";
            }
        }
    }
}